package com.haoran;

import com.haoran.initializer.CustomizableWebSocketChannelInitializer;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

class WebSocketServer {
	
	private static final int DEFAULT_WEB_SOCKET_PORT = 8888;

	public static void run() {
		run(DEFAULT_WEB_SOCKET_PORT);
	}

	public static void run(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workerGroup = new NioEventLoopGroup();
		try {
			ServerBootstrap sb = new ServerBootstrap();
			sb.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
					.childHandler(new CustomizableWebSocketChannelInitializer());
			Channel channel = sb.bind(port).sync().channel();
			System.out.println("Web socket server started at port " + port + ".");
			System.out.println("Open your browser and navigate to http://localhost:" + port + "/.");
			channel.closeFuture().sync();
		} catch (InterruptedException e) {
			bossGroup.shutdownGracefully();
			workerGroup.shutdownGracefully();
		}
	}
}
